<template>
  <a-modal v-model="visible" :title="title" :confirmLoading="submitLoading" width="800px" ok-text="确认" cancel-text="取消"
    @ok="addFormSubmit">
    <a-form :form="events_form" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <div v-if="isImg">
        <span v-if="imgUrls?.length > 0">
          <viewer :images="imgUrls">
            <div v-for="(item, index) in imgUrls" :key="index" class="uploadDiv"
              style="width: 180px;height: 180px;border: none;">
              <img :src="item" alt="" />
            </div>
          </viewer>
          <div style="clear: both;"></div>
        </span>
        <a-empty description="暂无图片" v-else />
      </div>
      <div v-else>
        <!-- <a-form-item label="板块类别">
          <a-select v-decorator="['categoryType']" @change="attendanceTypeChange" style="width: 501px;"
            placeholder="选择状态">
            <a-select-option :key="1">
              技能培训
            </a-select-option>
            <a-select-option :key="2">
              慰问关怀
            </a-select-option>
          </a-select>
        </a-form-item> -->
        <a-form-item label="业务描述">
          <a-input placeholder="请输入业务描述" v-decorator="['achievementsName']"></a-input>
        </a-form-item>
        <a-form-item label="业务内容">
          <a-input placeholder="请输入业务内容" v-decorator="['businessContent']"></a-input>
        </a-form-item>
        <a-form-item label="时间">
          <a-range-picker valueFormat="YYYY-MM-DD" v-decorator="['rangeDate']" style="width: 501px;" />
        </a-form-item>
        <a-form-item label="城市">
          <a-cascader v-decorator="['city']" :options="cityList" placeholder="请选择城市" @change="cityChange"
            style="width: 501px;" />
        </a-form-item>
        <a-form-item label="类别">
          <a-select v-decorator="['refineType']" style="width: 501px;" placeholder="选择类别">
            <a-select-option v-for="item in refineList" :value="item.code" :key="item.code">
              {{ item.desc }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="文件上传">
          <a-button type="primary" icon="plus" @click="uploadFile">上传文件</a-button>
          <span v-if="fileUrls?.length > 0">
            <div v-for="(item, index) in fileUrls" :key="index" class="uploadFile">
              <div class="text">{{ item | filterStr }}</div>
              <a-icon type="close-circle" theme="filled" class="iconClose" @click="delFileUpload(index)"/>
            </div>
          </span>
          <input type="file" ref="uploadFileRef" @change="handleFileChange" style="display: none;" />
        </a-form-item>
        <a-form-item label="图片">
          <span v-if="imgUrls?.length > 0">
            <div v-for="(item, index) in imgUrls" :key="index" class="uploadDiv">
              <img :src="item" alt="" />
              <a-icon type="close-circle" theme="filled" class="iconClose" @click="delUpload(index)"/>
            </div>
          </span>
          <div class="uploadDiv" @click="uploadImg"><a-icon type="plus" style="font-size: 32px;" /></div>
          <input type="file" ref="uploadImgRef" @change="handleChange" style="display: none;" />
        </a-form-item>
      </div>

    </a-form>
  </a-modal>
</template>

<script>
import {
  addDisabledAchievements,
  updateAchievements,
  selectAchievementsType,
  getPageArea
} from "@/api/human/disabled"
import { uploadNewFile } from "@/api/manage/base"
import store from '@/store'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'AddInfo',
  data() {
    return {
      title: "",
      visible: false,
      submitLoading: false,

      id: "",
      refineList: [], // 类别列表
      cityList: [], // 城市列表
      cityName: "",
      isImg: false, // 是否查看图片
      imgUrls: [], // 图片数组
      fileUrls: [], // 文件数组
      categoryType: 1,
    }
  },
  filters: {
    filterStr(value) {
      if (!value) return '--'
      return value.substring(value.lastIndexOf("/") + 1)
    },
  },
  beforeCreate() {
    this.events_form = this.$form.createForm(this, {
      name: 'events_form'
    });
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    // 打开编辑弹窗 
    async add(row, isImg, type) {
      this.visible = true;
      this.id = row === true ? '' : row.id;
      this.categoryType = row.categoryType;
      this.isImg = isImg;
      this.imgUrls = [];
      this.getCityList();
      
      if (row == true) {
        this.title = '新增';
        this.getSelectAchievementsType(type);
        this.categoryType = type;
        this.$nextTick(() => {
          this.events_form.resetFields();
        })
      } else {
        this.title = isImg ? '查看图片' : '修改';
        this.$nextTick(() => {
          let values = this.events_form.getFieldsValue();
          for (var key in row) {
            values[key] = row[key]
          }
          values['rangeDate'] = [row['businessTimeStart'], row['businessTimeEnd']];
          this.cityName = row['cityName'];
          this.fileUrls = row['fileUrls'] || [];
          this.imgUrls = row['imgUrls'] || [];
          this.events_form.setFieldsValue(values);
          this.getSelectAchievementsType(row.categoryType);
        })
      }
    },
    // 获取城市列表
    async getCityList() {
      const { code, data } = await getPageArea();
      if (code == '1') {
        this.cityList = data
      }
    },
    // 城市选择
    cityChange(value, item) {
      this.cityName = (item.map(city => city.label)).join('/');
    },
    // 时间选择
    rangePicker(e) {
      if (e) {
        this.businessTimeStart = e[0];
        this.businessTimeEnd = e[1];
      }
    },
    // 板块类别选择
    attendanceTypeChange(e) {
      this.getSelectAchievementsType(e);
    },
    // 获取类别列表
    async getSelectAchievementsType(type) {
      const { code, data } = await selectAchievementsType({ templateType: type });
      if (code == '1') {
        this.refineList = data
      }
    },
    // 文件上传
    uploadFile() {
      this.$refs.uploadFileRef.click()
    },
    async handleFileChange(e, filed) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) { return; }
      if (file.type.indexOf('pdf') === -1) {
        _this.$message.error("非pdf文件格式");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 100)) {
        _this.$message.error('文件大小不能超过 100MB!')
        e.target.value = "";
        return;
      }
      var params = new FormData();
      params.append("file", file);
      params.append("dirName", '技能培训文件');
      let { code, data } = await uploadNewFile(params);
      if (code == '1') {
        _this.fileUrls.push(data);
        e.target.value = "";
      }
    },
    // 删除文件
    delFileUpload(i) {
      this.fileUrls.splice(i, 1);
    },
    // 图片上传
    uploadImg() {
      this.$refs.uploadImgRef.click()
    },
    async handleChange(e, filed) {
      e.preventDefault();
      let _this = this;
      let file = e.target.files[0];
      if (file === undefined) { return; }
      if (file.type.indexOf('image') === -1) {
        _this.$message.error("非法图片格式");
        e.target.value = "";
        return;
      }
      if (!(file.size / 1024 / 1024 < 1)) {
        _this.$message.error('图片大小不能超过 1MB!')
        e.target.value = "";
        return;
      }
      var params = new FormData();
      params.append("file", file);
      params.append("dirName", '技能培训图片');
      let { code, data } = await uploadNewFile(params);
      if (code == '1') {
        _this.imgUrls.push(data);
        e.target.value = "";
      }
    },
    // 删除图片
    delUpload(i) {
      this.imgUrls.splice(i, 1);
    },
    // 提交
    async addFormSubmit() {
      this.events_form.validateFieldsAndScroll(async (err, values) => {
        if (!err) {
          if (this.id) {
            // 修改
            values.id = this.id;
          } else {
            // 新增
          }
          if (values.rangeDate?.length > 0) {
            values.businessTimeStart = values.rangeDate[0];
            values.businessTimeEnd = values.rangeDate[1];
          }
          values.cityName = this.cityName;
          values.fileUrls = this.fileUrls;
          values.imgUrls = this.imgUrls;
          values.categoryType = this.categoryType;
          this.submitLoading = true;
          const { code } = this.id ? await updateAchievements(values) : await addDisabledAchievements(values);
          this.submitLoading = false;
          if (code == '1') {
            this.visible = false;
            this.$message.success('操作成功');
            this.$emit('on-ok');
          }
        }
      });
    }
  }
}
</script>